import { mergeWith } from 'lodash';

import { isArray, isObject } from './is';

// 合并两个对象
 export const mergeObject = (source, other) => {
    if (!isObject(source) || !isObject(other)) {
      return other === undefined ? source : other
    }
    // 合并两个对象的 key，另外要区分数组的初始值为 []
    return Object.keys({
      ...source,
      ...other,
    }).reduce(
      (acc, key) => {
        // 递归合并 value
        acc[key] = mergeObject(source[key], other[key])
        
        return acc
      },
      Array.isArray(source) ? [] : {}
    )
  }
  
  export const mergeWithObject = (source, other) => {
    return mergeWith(source, other, function customizer(sourceValue, otherValue) {
      if (isArray(sourceValue)) {
          return otherValue;
      } else if (typeof sourceValue === 'object' && typeof otherValue === 'object') {
          // 若是object类型的对象，我们进行递归
          return mergeWith(sourceValue, otherValue, customizer)
      } else {
        return otherValue;
      }
    })
  }